{include file="public/header,public/nav,public/fixbar" title="章节练习-<?php echo request()->pc_info['seo_title']?>"/}
<style>
    .layui-layer-btn-c .layui-layer-btn0 {
        height: 38px !important;
        line-height: 38px !important;
        width: 160px !important;
        font-size: 16px !important;
    }
</style>
<div class="practice-header">
    <div class="layui-container" style="padding: 0 15px;">
        <div class="space-between">
            {if $source == 'practice'}
            <a href="javascript:;" class="align-items-center layui-font-16 exit-practice"><i class="layui-icon layui-icon-left margin-right-5"></i>返回</a>
            {else}
            <a href="javascript:history.back()" class="align-items-center layui-font-16"><i class="layui-icon layui-icon-left margin-right-5"></i>返回</a>
            {/if}
            <h3 class="justify-content-center"><img src="/static/images/rank/title_decorate_icon.png"><span class="practice-header-title">{$info.chapter_name}</span><img src="/static/images/rank/title_decorate_icon.png"></h3>
            <p></p>
        </div>
    </div>
</div>
<div class="layui-body padding-top-130">
    <div class="layui-container" style="margin-bottom: 120px;">
        <div class="layui-main min-height-55vh margin-bottom-10">
            <form class="layui-form" autocomplete="off" lay-filter="val-filter">
                <input name="practice_id" type="hidden" class="layui-input" value="{$info.practice_id ?? ''}">
                <div class="layui-card" style="border: none;">
                    <div class="layui-card-header layui-font-16">
                        <p>
                            <b style="font-family: DIN;" class="layui-font-24 layui-font-success" id="current">1</b>
                            <span class="text layui-font-18">/ {$info.total_question}题</span>
                        </p>
                    </div>
                    <div class="layui-card-body qustions-detail">
                        
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="practice-footer">
    <div class="layui-container" style="padding: 0 15px;">
        <div class="space-between height-80">
            <div class="item">
                <div class="layui-btn layui-btn-primary layui-btn-lg layui-btn-disabled" id="prev-btn" disabled>上一题</div>
                <div class="layui-btn layui-bg-success layui-btn-lg" id="next-btn" disabled>下一题</div>
                {if $source == 'practice'}
                    {if $info.set.practicemode == 1}
                        <div style="display: none;" class="layui-btn layui-bg-success layui-btn-lg exit-practice" id="submit-btn">结束背题</div>
                    {elseif $info.set.practicemode == 2}
                        <div style="display: none;" class="layui-btn layui-bg-success layui-btn-lg submit-exam" id="submit-btn">结束练习</div>
                    {else}
                        <div style="display: none;" class="layui-btn layui-bg-success layui-btn-lg submit-exam" id="submit-btn" >提交考试</div>
                    {/if}
                {else}
                    <a style="display: none;" href="/question/practice_report?practice_id={$info.practice_id}" class="layui-btn layui-btn-lg layui-bg-success layui-btn-fluid" id="submit-btn">查看报告</a>
                {/if}
            </div>
            <div class="align-items-center">
                <div class="operate-list-item practice-pause">
                    <i class="layui-icon layui-icon-pause layui-font-20"></i>
                    <p class="text">暂停</p>
                </div>
                <div class="operate-list-item answer-card-module" data-practice_id="{$info.practice_id}">
                    <i class="layui-icon layui-icon-date layui-font-20"></i>
                    <p class="text">答题卡</p>
                </div>
                <div class="operate-list-item question-favorite" data-practice_id="{$info.practice_id}">
                    <i class="layui-icon layui-icon-star layui-font-20"></i>
                    <p class="text">收藏</p>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 答题卡 -->
<div id="answer-card" style="display: none;">
    <div class="answer-card">
        <div class="answer-card-stats">
            <div class="status-legend">
                {if $source == 'practice'}
                    <div class="status-item">
                        <div class="status-color current-color"></div>
                        <span>当前</span>
                    </div>
                    {if $info.set.practicemode == 0}
                    <div class="status-item">
                        <div class="status-color answered-color"></div>
                        <span>已答</span>
                    </div>
                    <div class="status-item">
                        <div class="status-color unanswered-color"></div>
                        <span>未答</span>
                    </div>
                    {elseif $info.set.practicemode == 2}
                    <div class="status-item">
                        <div class="status-color answered-color"></div>
                        <span>答对</span>
                    </div>
                    <div class="status-item">
                        <div class="status-color wrong-color"></div>
                        <span>答错</span>
                    </div>
                    <div class="status-item">
                        <div class="status-color unanswered-color"></div>
                        <span>未答</span>
                    </div>
                    {else}
                    <div class="status-item">
                        <div class="status-color answered-color"></div>
                        <span>已刷</span>
                    </div>
                    <div class="status-item">
                        <div class="status-color unanswered-color"></div>
                        <span>未刷</span>
                    </div>
                    {/if}
                {else}
                    <div class="status-item">
                        <div class="status-color answered-color"></div>
                        <span>答对</span>
                    </div>
                    <div class="status-item">
                        <div class="status-color wrong-color"></div>
                        <span>答错</span>
                    </div>
                    <div class="status-item">
                        <div class="status-color unanswered-color"></div>
                        <span>未答</span>
                    </div>
                {/if}
            </div>
        </div>
        <div class="scrollbar" style="height: 260px;">
            {if $source == 'practice'}
            <div class="question-items" id="question-items">
                <!-- 答题卡题目项将通过jQuery动态生成 -->
            </div>
            {else}
            <div class="question-items">
                {foreach $info.question_list as $key => $v}
                    <div class="question-item {if $v.is_correct == 1}answered{elseif $v.is_correct == 0}wrong{/if}" data-index="{$key}" data-question-id="{$v.question_id}">{$key+1}</div>
                {/foreach}
            </div>
            {/if}
        </div>
        <div class="card-controls">
            {if $source == 'practice'}
                {if $info.set.practicemode == 0}
                <button class="layui-btn layui-btn-lg layui-bg-success layui-btn-fluid submit-exam">提交考试</button>
                {elseif $info.set.practicemode == 1}
                <button class="layui-btn layui-btn-lg layui-bg-success layui-btn-fluid exit-practice">结束背题</button>
                {elseif $info.set.practicemode == 2}
                <button class="layui-btn layui-btn-lg layui-bg-success layui-btn-fluid submit-exam">结束练习</button>
                {/if}
            {else}
                <a href="/question/practice_report?practice_id={$info.practice_id}" class="layui-btn layui-btn-lg layui-bg-success layui-btn-fluid">查看报告</a>
            {/if}
        </div>
    </div>
</div>

<script type="text/javascript">
    layui.use(['form','flow','layer','richTextToggle','element'], function(){
        var flow = layui.flow, layer = layui.layer, form = layui.form, richTextToggle = layui.richTextToggle, element = layui.element, $ = layui.$;
        form.render();

        // 全局变量
        let questionIds = '<?php echo json_encode($question_ids);?>'; // 所有题目ID
        questionIds = $.parseJSON(questionIds); 
        
        let currentQuestionIndex = {$question_index}; // 当前题目索引
        let currentTabQuestionId = 0; //材料题 tab 的题ID 
        var currentTabQuestionIndex = 0; // 当前材料题 tab 的索引
        let source = "{$source}"; // 来源
        let product_id = "{$info.id}"; // 产品ID
        let practice_mode = "{$info.set.practicemode}"; // 刷题模式 0考试模式、 1背题模式、2练题模式
        let practice_id = $("input[name=practice_id]").val(); // 练题记录ID
        let disabled = '';
        if (practice_mode == 1) {
            disabled = 'disabled';
        }
        // 初始化
        init();

        function init() {
            // 加载题目ID列表
            loadQuestionIds();

            // 绑定事件
            $('#prev-btn').click(prevQuestion);
            $('#next-btn').click(nextQuestion);
        }
        
        // 加载题目ID列表
        function loadQuestionIds() {
            // 初始化答题卡
            initAnswerCard();

            // 绑定答题卡事件
            bindAnswerCardEvents();
            
            // 加载第一题
            if (questionIds.length > 0) {
                loadQuestion(questionIds[currentQuestionIndex]);
                $('#next-btn').prop('disabled', false);
            }
        }

        // 上一题
        function prevQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion(questionIds[currentQuestionIndex]);
            }
        }
        
        // 下一题
        async function nextQuestion() {
            try {
                // 提交答案
                if (source == 'practice') {
                    var allTabs = $('.layui-tab-title li');
                    if (currentTabQuestionIndex === allTabs.length - 1 && currentTabQuestionIndex > 0) {
                        // 等待提交答案完成
                        await submitAnswer(currentTabQuestionId, currentQuestionIndex);
                    } else {
                        // 等待提交答案完成
                        await submitAnswer(questionIds[currentQuestionIndex], currentQuestionIndex);
                    }
                    
                }
                
                // 提交完成后检查是否还有下一题
                if (currentQuestionIndex < questionIds.length - 1) {
                    currentQuestionIndex++;
                    await loadQuestion(questionIds[currentQuestionIndex]);
                } else {
                    // 如果是最后一题，可以提示或执行其他操作
                    layer.msg('已经是最后一题了', {icon: 2});
                }
            } catch (error) {
                console.error('下一题操作失败:', error);
                layer.msg('操作失败，请重试', {icon: 2});
            }
        }

        // 提交答案
        function submitAnswer(question_id, currentQuestionIndex, is_end = 0) {
            return new Promise((resolve, reject) => {
                var loading = layer.load();
                var data = form.val('val-filter');
                data.question_id = question_id;
                data.is_end = is_end; // 是否结束提交
                $.ajax({
                    url:'/question/submit_answer',
                    type:'post',
                    data:data,
                    dataType:"JSON",
                    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                    success:function(res){
                        layer.close(loading);  //返回数据关闭loading
                        if(res.code == 0){
                            // 更新答题卡状态
                            var is_correct = res.data.is_correct;
                            var answer = res.data.answer;
                            if (practice_mode == 0) {
                                updateAnswerCardItem(currentQuestionIndex, answer.length > 0 ? 'answered' : '');
                            } else if (practice_mode == 1) {
                                updateAnswerCardItem(currentQuestionIndex, 'answered');
                            } else {
                                updateAnswerCardItem(currentQuestionIndex, is_correct ? 'answered' : 'wrong');
                            }
                            resolve(res.data);
                            if (is_end == 1 && practice_mode != 1) {
                                // 结束练习/交卷后跳转报告页
                                location.href = '/question/practice_report?practice_id='+practice_id;
                            }
                        } else{
                            layer.msg(res.msg,{icon: 2});
                            reject(res.msg || '提交失败');
                        }
                    },
                    error:function(e){
                        layer.close(loading);
                        layer.msg('请求失败'+e.responseText,{icon: 2});
                        reject('网络错误: ' + error);
                    },
                    
                });
            })
        }

        // 答案
        function answerContent(knownAnswer, youAnswer = '') {
            if (!knownAnswer) {
                knownAnswer = '--';
            } else {
                knownAnswer = knownAnswer.toUpperCase()
            }

            if (!youAnswer) {
                youAnswer = '--';
            } else {
                youAnswer = youAnswer.toUpperCase()
            }
            
            var youAnswerHtml = '';
            if (practice_mode != 1) {
                // 背题模式
                youAnswerHtml = `<div class="questions-answer-item">
                                    <span>你的答案：</span>
                                    <span class="result layui-font-red you-result">${youAnswer}</span>
                                </div>`;
            }
            var html = `<div class="questions-answer">
                                <div class="questions-answer-item">
                                    <span>正确答案：</span>
                                    <span class="result layui-font-success known-result">${knownAnswer}</span>
                                </div>
                                ${youAnswerHtml}
                            </div>`;
            if ((practice_mode == 0) && source == 'practice') {
                // 考试模式
                html = '';
            }
            return  html;
        }

        // 题目解析
        function analyzeContent(analyze, questionId) {
            var html = `<div class="question-analyze">
                            <div class="zent-block-header block-header" style="padding: 0;">
                                <div class="zent-block-header__title zent-block-header__title-ribbon">
                                    <h3>题目解析</h3>
                                </div>
                                <div class="layui-btn layui-btn-primary error-recovery" user-login data-question-id="${questionId}">
                                    <i class="iconfont icon-jiucuo margin-right-5 layui-font-14"></i>题纠错
                                </div>
                            </div>
                            <div class="layui-card-body">
                                ${analyze}
                            </div>
                        </div>`;

            if ((practice_mode == 0) && source == 'practice') {
                // 考试模式
                html = '';
            }
            return html;
        }

        // 笔记答疑
        function noteContent(questionId) {
            var html = `<div class="question-note">
                            <div class="zent-block-header block-header" style="padding: 0;">
                                <div class="zent-block-header__title zent-block-header__title-ribbon">
                                    <h3>笔记答疑</h3>
                                </div>
                                <div class="layui-btn layui-bg-success take-note" user-login data-question-id="${questionId}">
                                    <i class="iconfont icon-yijianfankui margin-right-5 layui-font-14"></i>写笔记
                                </div>
                            </div>
                            <div class="layui-card-body">
                                <div id="note-list-${questionId}">

                                </div>
                            </div>
                        </div>`;

            if ((practice_mode == 0) && source == 'practice') {
                // 考试模式
                html = '';
            }
            return html;
        }

        // 选择题型（包含单选、多选、判断）
        function choiceQuestionType(item) {
            var html = '';
            // 单选题、多选题、判断题
            layui.each(item.options, function(index, val){
                var multiple = '';
                var select = '';
                var checked = '';
                var lay_way = 'lay-radio';
                if (item.type == 2 || item.type == 8) {
                    lay_way = 'lay-checkbox';
                    multiple = 'options-multiple'
                    if (item.practice_detail && item.practice_detail.answer) {
                        // 检查当前选项值是否在答案数组中
                        if (item.practice_detail.answer.includes(val['k'])) {
                            checked = 'checked';
                        }
                    }
                    select = `<input type="checkbox" name="answer_${item.id}[]" value="${val['k']}" lay-skin="none" ${checked} ${disabled}>`
                } else {
                    if (item.practice_detail && (item.practice_detail.answer[0] == val['k'])) {
                        checked = 'checked'
                    }
                    select = `<input type="radio" name="answer_${item.id}[]" value="${val.k}" data-id="${item.id}" lay-skin="none" lay-filter="answer-filter" ${checked} ${disabled}> `;
                }
                var lable = `<div class="lable">${val['k']}</div>`
                if (item.type == 3) {
                    val['k'] = val['k'].toUpperCase()
                    lable = `<div class="lable">${val['k']}</div>`
                }
                html += `<div class="layui-row margin-bottom-5">
                            ${select}
                            <div ${lay_way} class="lay-skin-checkcard">
                                <div class="lay-skin-checkcard-detail">
                                    <div class="options ${multiple}">
                                        ${lable}
                                        <div class="content">${val['c']}</div>
                                    </div>
                                </div>
                            </div>
                        </div>`;
            })
            return html;
        }

        // 填空题型
        function fillinQuestionType(item) {
            var fill_tab = '';
            var fill_tab_item = '';
            var html = '';
            layui.each(item.options, function(index, val){
                var layui_this = '';
                var layui_show = '';
                var answer = '';
                if (item.practice_detail) {
                    answer = item.practice_detail.answer[index]
                }
                if (index == 0) {
                    layui_this = 'layui-this';
                    layui_show = 'layui-show';
                }
                fill_tab += `<li class="layui-font-16 ${layui_this}">第${index+1}空</li>`;
                fill_tab_item += `<div class="layui-tab-item ${layui_show}">
                                    <textarea name="answer_${item.id}[]" placeholder="请输入你的答案" class="layui-textarea" ${disabled}>${answer}</textarea>
                                </div>`
            })
            html += `<div style="padding: 0px 10px;">
                            <div class="layui-tab layui-tab-brief">
                                <ul class="layui-tab-title">
                                    ${fill_tab}
                                </ul>
                                <div class="layui-tab-content">
                                    ${fill_tab_item}
                                </div>
                            </div>
                        </div>`;
            return html;
        }

        // 简答题型
        function shortAnswerQuestionType(item) {
            var html = '';
            var answer = '';
            if (item.practice_detail) {
                var answer = item.practice_detail.answer[0]
            }
            // 问答题、写作题、论述题
            html = `<div class="options">
                            <textarea name="answer_${item.id}[]" placeholder="请输入你的答案" class="layui-textarea" ${disabled}>${answer}</textarea>
                        </div>`;
            return html;
        }

        // 材料题型 checkResult练题模式查看解析
        function materialQuestionType(children){
            // 材料题
            var tab = '';
            var tab_item = '';
            var c_answerHtml = '';
            var c_analyzeHtml = '';
            var c_noteHtml = '';
            layui.each(children, function(m_key, m_v){
                var you_answer = '';
                if (m_v.practice_detail) {
                    you_answer = m_v.practice_detail.answer_str
                }
                
                if (m_v.type == 1 || m_v.type == 2 || m_v.type == 3 || m_v.type == 8) {
                    c_answerHtml = answerContent(m_v.answer, you_answer);
                }
                c_analyzeHtml = analyzeContent(m_v.analyze, m_v.id);
                c_noteHtml = noteContent(m_v.id);
                var checkAnalyzeHtml = `<div class="analyze-options">${c_answerHtml + c_analyzeHtml + c_noteHtml}</div>`;
                if (practice_mode == 2 && source == 'practice') {
                    // 练题模式
                    checkAnalyzeHtml = `<div class="analyze-btn">
                                            <div class="text-align-center">
                                                <div class="layui-btn layui-btn-primary check-analyze width-150" data-id="${m_v.id}">查看解析</div>
                                            </div>
                                            <div class="analyze-options layui-hide">${c_answerHtml + c_analyzeHtml + c_noteHtml}</div>
                                        </div>`
                }

                var layui_this = '';
                var layui_show = '';
                var c_options = '';
                if (m_key == 0) {
                    layui_this = 'layui-this'
                    layui_show = 'layui-show'
                }
                tab += `<li class="layui-font-16 ${layui_this}" lay-id="${m_v.id}">第${m_key+1}题</li>`;

                if (m_v.type == 4 || m_v.type == 6 || m_v.type == 7) {
                    // 问答题、写作题、论述题
                    c_options = shortAnswerQuestionType(m_v)+checkAnalyzeHtml;
                } else if (m_v.type == 5) {
                    // 填空题
                    c_options = fillinQuestionType(m_v)+checkAnalyzeHtml;
                } else {
                    // 选择题
                    c_options = choiceQuestionType(m_v)+checkAnalyzeHtml;
                }
                tab_item += `<div class="layui-tab-item ${layui_show}">
                                <div id="question_${m_v.id}">
                                    <div class="qustions-item">
                                        <span class="lable">${m_v.type_name}</span>
                                        <span class="text">${m_v.question}</span>
                                    </div>
                                </div>
                                <div class="children-question-options" data-id="${m_v.id}">
                                    ${c_options}
                                </div>
                            </div>`;
            })
            options = `<div style="padding: 0px 10px;">
                            <div class="layui-tab layui-tab-brief" lay-filter="question-tab">
                                <ul class="layui-tab-title">
                                    ${tab}
                                </ul>
                                <div class="layui-tab-content">
                                    ${tab_item}
                                </div>
                            </div>
                        </div>`;
            
            return options;
        }

        // 材料题 tab 切换前的事件
        element.on('tabBeforeChange(question-tab)', function(data){
            var question_id = data.from.id; // 得到切换前的 tab 项所在ID
            var to_question_id = data.to.id // 得到切换后的 tab 项所在ID
            
            currentTabQuestionId = to_question_id;
            currentTabQuestionIndex = data.to.index;
            // 获取笔记记录
            loadNoteList(to_question_id);
            // 提交答案
            if ((practice_mode == 0 || practice_mode == 1 || practice_mode == 2) && source == 'practice') {
                submitAnswer(question_id, currentQuestionIndex);
            }
        });
        
        // 练题模式单选答案后立即显示解析
        form.on('radio(answer-filter)', function(data){
            var elem = data.elem; // 获得 radio 原始 DOM 对象
            var question_id = elem.getAttribute('data-id');
            // 查看解析
            if (practice_mode == 2 && source == 'practice') {
                
            }
        });

        // 获取题目信息
        function loadQuestion(questionId) {
            return new Promise((resolve, reject) => {
                var loading = layer.load();
                $.ajax({
                    url:'/question/get_question_info',
                    type:'post',
                    data:{"practice_id":practice_id, "question_id":questionId, "source":source},
                    dataType:"JSON",
                    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                    success:function(res){
                        layer.close(loading);
                        if(res.code == 0){
                            var item = res.data;

                            var you_answer = '';
                            if (item.practice_detail) {
                                you_answer = item.practice_detail.answer_str
                            }
                            if (item.type == 1 || item.type == 2 || item.type == 3 || item.type == 8) {
                                var answerHtml = answerContent(item.answer, you_answer);
                            } else {
                                var answerHtml = '';
                            }
                            var analyzeHtml = analyzeContent(item.analyze, item.id);
                            var noteHtml = noteContent(item.id);

                            var checkAnalyzeHtml = `<div class="analyze-options">${answerHtml + analyzeHtml + noteHtml}</div>`;
                            if (practice_mode == 2 && source == 'practice') {
                                // 练题模式
                                checkAnalyzeHtml = `<div class="analyze-btn">
                                                        <div class="text-align-center">
                                                            <div class="layui-btn layui-btn-primary check-analyze width-150" data-id="${item.id}">查看解析</div>
                                                        </div>
                                                        <div class="analyze-options layui-hide">${answerHtml + analyzeHtml + noteHtml}</div>
                                                    </div>`
                            }

                            // 收藏处理
                            if (item.is_collect) {
                                $(".question-favorite").find('i').removeClass("layui-icon-star").addClass("layui-icon-star-fill");
                                $(".question-favorite").find('i').css("color","#ff5722");
                            } else {
                                $(".question-favorite").find('i').removeClass("layui-icon-star-fill").addClass("layui-icon-star");
                                $(".question-favorite").find('i').css("color","#60656b");
                            }
                            var newHtml = '';
                            var options = '';
                            var title = `<span class="text">${item.question}</span>`;
                            if (item.type == 9) {
                                // 材料题
                                title = `<span class="text">根据以下材料，回答问题</span>
                                        <div class="layui-elem-quote margin-top-15">
                                            <div class="rich-text-container">
                                                <div class="rich-text-content">${item.material}</div>
                                            </div>
                                        </div>`;

                                options = materialQuestionType(item.children);
                                
                            } else {
                                if (item.type == 4 || item.type == 6 || item.type == 7) { // 问答题、写作题、论述题
                                    options = shortAnswerQuestionType(item)+checkAnalyzeHtml;
                                } else if (item.type == 5) { // 填空题
                                    options = fillinQuestionType(item)+checkAnalyzeHtml;
                                } else { // 选择题
                                    options = choiceQuestionType(item)+checkAnalyzeHtml;
                                }
                                
                            }
                            var newHtml = `<div class="qustions-item">
                                                <span class="lable">${item.type_name}</span>
                                                ${title}
                                            </div>
                                            <div class="question-options" data-id="${item.id}">
                                                ${options}
                                            </div>`;

                            $(".qustions-detail").html(newHtml);
                            form.render();
                            if (item.type == 9) {
                                // 获取笔记记录
                                loadNoteList(item.children[0]['id']);
                            } else {
                                // 获取笔记记录
                                loadNoteList(questionId);
                            }
                            // 更新进度
                            $('#current').text(currentQuestionIndex + 1);
                            
                            // 更新答题卡当前题目状态
                            updateAnswerCardCurrent();

                            // 更新按钮状态
                            updateButtonState(currentQuestionIndex, questionIds)

                            // 返回顶部
                            scrollTop();

                            resolve(res.data);
                        } else{
                            layer.msg(res.msg,{icon: 2});
                            reject(res.msg || '加载题目失败');
                        }
                    },
                    error:function(e){
                        layer.close(loading);
                        layer.msg('请求失败'+e.responseText,{icon: 2});
                    },
                    
                });
            })
            
        }

        // 返回底部
        function scrollTop() {
            $('html, body').animate({scrollTop: 0}, 300);
        }

        // 初始化
        richTextToggle.init('.rich-text-content', {
            maxLines: 10, // 显示更多行
            expandText: '展开全部',
            collapseText: '收起全文',
            showMask: false // 不需要遮罩
        });

        // 更新按钮状态
        function updateButtonState(currentQuestionIndex, questionIds) {
            if (currentQuestionIndex + 1 > 1) {
                $("#prev-btn").removeClass("layui-btn-disabled").addClass("layui-border-success");
                $('#prev-btn').prop('disabled', false);
            } else {
                $("#prev-btn").addClass("layui-btn-disabled").removeClass("layui-border-success");
                $('#prev-btn').prop('disabled', true);
            }
            
            // 如果是最后一题，显示提交按钮
            if (currentQuestionIndex === questionIds.length - 1) {
                $('#next-btn').hide();
                $('#submit-btn').show();
            } else {
                $('#next-btn').show();
                $('#submit-btn').hide();
            }
        }

        // 练习暂停
        $(".practice-pause").click(function(){
            layer.confirm('<div class="text-align-center"><img src="/static/images/pause_modal_icon.png"><p class="layui-font-22 font-weight-bold margin-top-30">休息一下，稍后继续</p></div>', {
                area: ['420px', '340px'],
                title:false, 
                shadeClose: true,
                closeBtn: 0,
                btnAlign: 'c',
                btn: ['继续做题'],
            }, function(index){
                layer.close(index);
            });
        })

        // 题目收藏
        $(".question-favorite").click(function(){
            var loading = layer.load();
            var practice_id = $(this).data('practice_id');
            $.ajax({
                url:"/question/favorites_add",
                type:'post',
                data:{"question_id":questionIds[currentQuestionIndex], "practice_type":"chapter", "practice_id":practice_id},
                dataType:'JSON',
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                success:function(res){
                    layer.close(loading);
                    if(res.code==0){
                        layer.msg(res.msg,{icon: 1,time: 1500},function(){
                            if (res.data == 1) {
                                $(".question-favorite").find('i').removeClass("layui-icon-star").addClass("layui-icon-star-fill");
                                $(".question-favorite").find('i').css("color","#ff5722");
                            } else {
                                $(".question-favorite").find('i').removeClass("layui-icon-star-fill").addClass("layui-icon-star");
                                $(".question-favorite").find('i').css("color","#60656b");
                            }
                        });
                    }else{
                        layer.msg(res.msg,{icon: 2,time: 2000});
                    }
                },
                error:function(e){
                    layer.msg('请求失败'+e.responseText,{icon: 2});
                },
            });
        })

        // 题目纠错
        $(document).on('click', '.error-recovery',function(){
            var user_id = "{:session('user.id')}";
            var question_id = $(this).attr('data-question-id');
            if (user_id) {
                var index = layer.open({
                    skin: 'layui-layer-radius', // 弹窗主题样式
                    offset: 'auto',
                    title: '题目纠错',
                    type: 2,
                    anim: 'slideUp',
                    shade: 0.3,
                    shadeClose: true,
                    area: ['620px', '460px'],
                    content: '/question/correction?question_id='+question_id
                });
                var device = layui.device('mobile');
                if (device.mobile) {
                    layer.full(index);
                }
            }
        })

        // 写笔记
        $(document).on('click', '.take-note',function(){
            var user_id = "{:session('user.id')}";
            var question_id = $(this).attr('data-question-id');
            if (user_id) {
                var index = layer.open({
                    skin: 'layui-layer-radius', // 弹窗主题样式
                    offset: 'auto',
                    title: '写笔记',
                    type: 2,
                    anim: 'slideUp',
                    shade: 0.3,
                    shadeClose: true,
                    area: ['620px', '460px'],
                    content: '/question/note?question_id='+question_id
                });
                var device = layui.device('mobile');
                if (device.mobile) {
                    layer.full(index);
                }
            }
        })

        // 笔记列表
        window.loadNoteList = function(question_id) {
            var elem = $('#note-list-'+question_id);
            elem.html('');
            var limit = 5;//每次请求的条数
            flow.load({
                elem: elem //指定列表容器
                ,scrollElem: ''//滚动条所在元素
                ,end: '—— 已经到底了~ ——'
                ,isAuto: false
                ,done: function(page, next){ //到达临界点（默认滚动触发），触发下一页的回调
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        data: {'page': page, 'limit':limit, 'question_id':question_id},//请求的页码和每页显示条数
                        url: '/question/get_note',
                        success: function (res) {
                            var lis = [];
                            if(res.code == 0){
                                if (res.data.length > 0) {
                                    var newsHtml = '';
                                    layui.each(res.data, function(index, item){
                                        var like = `<i style="cursor: pointer;" class="iconfont icon-icon_good1 layui-font-20"></i>`;
                                        if (item.is_like == 1) {
                                            like = `<i style="cursor: pointer;" class="iconfont icon-icon_good1_fill layui-font-20 layui-font-orange"></i>`;
                                        }
                                        var edit = '';
                                        if (item.self == 1) {
                                            edit = `<span class="layui-btn layui-btn-primary layui-btn-sm edit-note" data-id="${item.id}"><i class="layui-icon layui-icon-edit"></i> 编辑</span>`
                                        }
                                        newsHtml += `<div class="note-list-item">
                                                        <div>
                                                            <img src="${item.user.avatar}" class="layui-nav-img" style="width: 50px;height: 50px;">
                                                        </div>
                                                        <div class="note-content">
                                                            <div class="space-between margin-bottom-10">
                                                                <div class="align-items-center">
                                                                    <div>
                                                                        <p class="margin-bottom-5 layui-font-l6 font-weight-bold">${item.user.nickname_two}</p>
                                                                        <p class="padding-right-20">${item.content}</p>
                                                                    </div>
                                                                </div>
                                                                <div>
                                                                    ${edit}
                                                                </div>
                                                            </div>
                                                            <div class="space-between">
                                                                <p class="text">${item.create_time}</p>
                                                                <div class="note-like align-items-end" data-id="${item.id}">
                                                                    <span class="layui-font-16 margin-right-8 like-count">${item.like}</span>
                                                                    ${like}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>`;
                                    });
                                    
                                    lis.push(newsHtml);
                                    //执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
                                    //res.total为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
                                    next(lis.join(''), page < Math.ceil(res.count/limit));
                                    
                                } else {
                                    elem.html('<div class="layui-empty"><img src="/static/images/nodata/no_question_bank.png"><p>暂无笔记内容~</p></div>');
                                }
                            } else {
                                layer.msg(res.msg, {icon:2, time: 1500});
                            }
                        }
                        ,error:function(e){
                            layer.msg("请求失败："+e.msg, {icon:2, time: 1500});
                        },
                    });
                }
            });
        }

        // 修改笔记
        $(document).on('click', '.edit-note',function(){
            var user_id = "{:session('user.id')}";
            var id = $(this).data('id');
            if (user_id) {
                var index = layer.open({
                    skin: 'layui-layer-radius', // 弹窗主题样式
                    offset: 'auto',
                    title: '写笔记',
                    type: 2,
                    anim: 'slideUp',
                    shade: 0.3,
                    shadeClose: true,
                    area: ['620px', '460px'],
                    content: '/question/note?question_id='+questionIds[currentQuestionIndex]+'&id='+id
                });
                var device = layui.device('mobile');
                if (device.mobile) {
                    layer.full(index);
                }
            }
        })

        // 笔记点赞/取消
        $(document).on('click', '.note-like',function(){
            var loading = layer.load();
            var note_id = $(this).data('id');
            var $this = $(this); // 保存当前点击的元素

            // 获取当前点赞数
            var $likeCount = $this.find('.like-count');
            var currentCount = parseInt($likeCount.text()) || 0;

            $.ajax({
                url:"/question/note_like",
                type:'post',
                data:{"note_id":note_id},
                dataType:'JSON',
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                success:function(res){
                    layer.close(loading);
                    if(res.code==0){
                        var isLiked = res.data;
                        var newCount = isLiked == 1 ? currentCount + 1 : currentCount - 1;
                        
                        // 更新UI
                        var $icon = $this.find('i');

                        if (isLiked) {
                            $icon.removeClass("icon-icon_good1").addClass("icon-icon_good1_fill layui-font-orange");
                            $likeCount.text(newCount).css({transform: 'scale(1.2)'});
                            setTimeout(function() {
                                $likeCount.css({transform: 'scale(1)'});
                            }, 300);
                            layer.msg('点赞成功', {icon: 1, time: 1000});
                        } else {
                            $icon.removeClass("icon-icon_good1_fill layui-font-orange").addClass("icon-icon_good1");
                            $likeCount.text(newCount);
                            layer.msg('已取消点赞', {icon: 1, time: 1000});
                        }
                    }else{
                        layer.msg(res.msg,{icon: 2,time: 2000});
                    }
                },
                error:function(e){
                    layer.msg('请求失败'+e.responseText,{icon: 2});
                },
            });
        })

        // 答题卡
        $(".answer-card-module").click(function(){
            // 获取按钮的位置和尺寸
            var btn = $(this);
            var btnOffset = btn.offset();
            var btnWidth = btn.outerWidth();
            var btnHeight = btn.outerHeight();

            // 设定弹窗的尺寸
            var popupWidth = 380;
            var popupHeight = 465;
            
            // 计算弹窗位置：水平居中于按钮，垂直位于按钮上方
            var topPosition = btnOffset.top - popupHeight - 15; // 上方10px间距
            var leftPosition = btnOffset.left + (btn.outerWidth() - popupWidth) / 2;

            // 计算箭头位置 - 指向按钮中心
            var arrowLeft = btnOffset.left + btnWidth / 2 - leftPosition;
            
            // 创建弹窗内容，包含箭头
            var content = '<div class="popup-container">' + $('#answer-card').html() + '<div class="popup-arrow bottom" style="left:' + arrowLeft + 'px"></div></div>';

            layer.open({
                title: '答题卡',
                type: 1,
                anim: 'slideUp',
                shadeClose: true,
                area: [popupWidth + 'px', popupHeight + 'px'], // 弹窗尺寸[citation:3]
                offset: ['371px', leftPosition + 'px'],
                content: content, 
                success: function(layero, index) {
                    // 确保弹窗内容可以溢出显示箭头
                    $(layero).find('.layui-layer-content').css({
                        'overflow': 'visible',
                    });
                }
            });
        })

        // 初始化答题卡
        function initAnswerCard() {
            const questionItemsContainer = $('#question-items');
            questionItemsContainer.empty();
            
            // 检查questionIds是否有数据
            if (questionIds.length === 0) {
                layer.msg('无法初始化答题卡，请刷新页面重试',{icon:2, time:2000})
                return false;
            }
            layui.each(questionIds, function(index, questionId) {
                const questionItem = $('<div>')
                    .addClass('question-item')
                    .text(index + 1)
                    .attr('data-index', index)
                    .attr('data-question-id', questionId);
                
                questionItemsContainer.append(questionItem);
            });
        }

        // 使用事件委托绑定点击事件 - 在初始化函数外绑定 因为.question-item是动态生成的
        function bindAnswerCardEvents() {
            $(document).off('click', '.question-item').on('click', '.question-item', function() {
                const index = $(this).attr('data-index');
                const questionId = $(this).attr('data-question-id');
                jumpToQuestion(parseInt(index));
            });
        }

        // 跳转到指定题目
        function jumpToQuestion(index) {
            currentQuestionIndex = index;
            loadQuestion(questionIds[currentQuestionIndex]);
        }

        // 更新答题卡当前题目状态
        function updateAnswerCardCurrent() {
            $('.question-item').removeClass('current');
            const $currentItem = $('.question-item[data-index="' + currentQuestionIndex + '"]');
            $currentItem.addClass('current');
        }

        // 更新答题卡题目项状态
        function updateAnswerCardItem(index, status) {
            const $item = $('.question-item').eq(index);
            $item.removeClass('current');
            
            if (status === 'answered') {
                $item.addClass('answered');
            } else if (status === 'wrong') {
                $item.addClass('wrong');
            }
            
            // 重新标记当前题目
            $('.question-item').eq(currentQuestionIndex).addClass('current');
        }

        // 提交考试
        $(document).on('click', '.submit-exam',function(){
            // 提交答案
            submitAnswer(questionIds[currentQuestionIndex], currentQuestionIndex, 1);
        })
        
        // 练题模式查看解析
        $(document).on('click', '.check-analyze',function(){
            var data = form.val('val-filter');
            var question_id = $(this).data('id');
            // if ((practice_mode == 2) && source == 'practice') {
            //     // 提交答案
            //     submitAnswer(question_id, currentQuestionIndex);
            // }
            var userAnswers = getAnswerStringFromForm(data, question_id);
            var $analyzeOptions = $(this).parent().siblings('.analyze-options');
            if (userAnswers) {
                $analyzeOptions.find('.questions-answer .questions-answer-item .you-result').text(userAnswers.toUpperCase());
            }
            if ($analyzeOptions.hasClass('layui-hide')) {
                $analyzeOptions.removeClass('layui-hide');
                $(this).hide();
            } else {
                $analyzeOptions.addClass('layui-hide');
                $(this).show();
            }
        })

        // 根据题目ID获取答案
        function getAnswerStringFromForm(data, question_id) {
            if (!data) return '';
            
            // 查找该题目的所有答案
            var answerValues = [];
            Object.keys(data).forEach(function(key) {
                if (key.startsWith('answer_' + question_id + '[')) {
                    answerValues.push({
                        key: key,
                        value: data[key]
                    });
                }
            });
            
            // 如果有多个选项，按索引排序后拼接
            if (answerValues.length > 0) {
                answerValues.sort(function(a, b) {
                    var indexA = parseInt(a.key.match(/\[(\d+)\]/)[1]);
                    var indexB = parseInt(b.key.match(/\[(\d+)\]/)[1]);
                    return indexA - indexB;
                });
                
                return answerValues.map(function(item) {
                    return item.value;
                }).join('');
            }
            return '';
        }

        // 返回结束练习、结束背题
        $(document).on('click', '.exit-practice',function(){
            var tips = '你要结束本次考试吗？'
            if (practice_mode == 1) { // 背题模式
                tips = '你要结束本次背题吗？'
            } else if (practice_mode == 2) {
                tips = '你要结束本次练习吗？'
            }
            layer.confirm(tips, {
                skin: 'layui-layer-radius', // 弹窗主题样式
                title : '操作确认',
            },function(index){
                // 提交答案
                submitAnswer(questionIds[currentQuestionIndex], currentQuestionIndex, 1);

                location.href="/question/chapter_detail?id="+product_id
            });
        })
    });
</script>